<?php

	// +----------------------------------------------------------------------
	// | 中国省市区三级联动插件
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace addon\china_city;

	use think\Event;
	use think\facade\Cache;
	use think\facade\Db;
	use yicmf\addon\controller\Controller;

	class ChinaCity extends Controller
	{

		public function install()
		{
		}

		public function uninstall()
		{
		}
		public function subscribe(Event $event)
		{
			$event->listen('china_city', [$this,'chinaCity']);
			$event->listen('china_city_info', [$this,'chinaCityInfo']);
		}
		public function chinaCity($param)
		{
			if (isset($param['admin']) && $param['admin'] == 1) { // bjui专用
				$default_config = $this->getConfig();
				if (Cache::has('addon_china_city_province_array')) {
					$addon_china_city_province_array = Cache::get('addon_china_city_province_array');
				} else {
					$addon_china_city_province_array = Db::name('District')->where('upid', 0)->where('level', 1)->field('id,name')->select();
					Cache::set('addon_china_city_province_array', $addon_china_city_province_array, 86400);
				}
				if ($param['value']) {
					//默认只需要区域id，则配置其他信息
					$district = Db::name('district')->find($param['value']);
					if ($district) {
						$city = Db::name('district')->find($district['upid']);
						if ($city) {
							$province = Db::name('district')->find($city['upid']);
						}
					}
				}
				$this->assign('name', isset($param['name']) ? $param['name'] : 'district_id');
				$this->assign('addon_china_city_province_array', $addon_china_city_province_array);
				$this->assign('addon_china_city_province', isset($province) ? $province['id'] : $default_config['province']);
				$this->assign('addon_china_city_city', isset($city) ? $city['id'] : $default_config['city']);
				$this->assign('addon_china_city_district', isset($district) ? $district['id'] : $default_config['district']);

				return $this->fetch('admin');
			} else {
//				$this->assign('default_config', $this->getConfig());
				$this->assign('param', $param);

				return $this->fetch('chinacity');
			}
		}

		public function chinaCityInfo($param)
		{
			if (!is_string($param)) {
				$province = Db::name('district')->where('id', $param['province_id'])->value('name');
				$city = Db::name('district')->where('id', $param['city_id'])->value('name');
				$district = Db::name('district')->where('id', $param['district_id'])->value('name');
				return $province . ' ' . $city . ' ' . $district;
			} else {
				return Db::name('district')->where('id', $param)->value('name');
			}
		}
	}
